package com.ai.wxy.spring.auth.security;

import com.ai.wxy.spring.auth.dto.JwtUserDTO;
import com.ai.wxy.spring.auth.util.JwtTokenUtil;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token权限验证
 *
 * @author 石头
 * @Date 2019/10/30
 * @Version 1.0
 **/
@Slf4j
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {
    private UserDetailsService userDetailsService;
    private final String tokenHeader;
    private final JwtTokenUtil jwtTokenUtil;
    public JwtAuthorizationTokenFilter(JwtTokenUtil jwtTokenUtil,UserDetailsService userDetailsService){
        this.tokenHeader  = jwtTokenUtil.getTokenHeader();
        this.jwtTokenUtil = jwtTokenUtil;
        this.userDetailsService = userDetailsService;
    }
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        final String requestHeader = request.getHeader(this.tokenHeader);

        String username  = null;
        String authToken = null;
        if (requestHeader != null && requestHeader.startsWith(JwtTokenUtil.getTokenPrefix())) {
            authToken = requestHeader.substring(7);
            try {
                username = jwtTokenUtil.getUsernameFromToken(authToken);
            } catch (ExpiredJwtException e) {
                log.error(e.getMessage());
            }
        }
        // 有token，且还没有生成凭证
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            JwtUserDTO userDetails = (JwtUserDTO)this.userDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                //authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }

        chain.doFilter(request, response);
    }
}
